package cn.fancy.sdk.floatwindow;

import static cn.fancy.sdk.login.utils.HttpReq.doFloatWebRequest;

import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import cn.fancy.sdk.JudgeMIUI;
import cn.fancy.sdk.common.utils.NetworkImpl;
import cn.fancy.sdk.common.utils.ResUtil;
import cn.fancy.sdk.entity.GuildBaseInfo;
import cn.fancy.sdk.utils.CommMessage;
import cn.fancy.sdk.utils.SpMmkvUtils;
import cn.fancy.sdk.utils.TipMessSingle;
import java.lang.reflect.Method;
import java.util.Objects;

public class FloatBallView extends LinearLayout {
	private static final int LEFT=1;
	private static final int RIGHT=2;
	private static final int TOP=3;
	private static final int BOTTOM=4;
	
	public static int viewWidth;
	public static int viewHeight;
	
	private final WindowManager windowManager;
	private WindowManager.LayoutParams mParams;
	private float xInScreen;
	private float yInScreen;
	private float xDownInScreen;
	private float yDownInScreen;
	private float xInView;
	private float yInView;
	private final Context mcontext;
	private final Handler handler;
	public static int moveaction; // 1 表示未触动状态 2 表示触动状态 3表示在桌面状态
	private final ImageView mRedpoint;
	private int screenWidth, screenHeight;
	private FloatWebView mFloatWebView = null;

	public FloatBallView(Context context) {
		super(context);
		mcontext = context;
		windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		handler = new Handler();
		moveaction = 1;
		LayoutInflater.from(context).inflate(
				ResUtil.getLayoutId(context, "guild_floatwindow"), this);
		View view = findViewById(ResUtil.getId(context, "small_window_layout"));
		viewWidth = view.getLayoutParams().width;
		viewHeight = view.getLayoutParams().height;

		mRedpoint = (ImageView) findViewById(ResUtil.getId(context, "badgeview"));
		if (FloatWebView.redpointModule == 0) {
			mRedpoint.setVisibility(View.INVISIBLE);
			Log.e("FloatWindowViewredpoint", "FloatWindowViewredpoint");
		} else {
			mRedpoint.setVisibility(View.VISIBLE);
		}
		
		String metaFloat=GuildBaseInfo.getInstance().getMetaUrl(context, "ICON");
		ImageView iv = (ImageView) findViewById(ResUtil.getId(context, "float_percent"));
		iv.setImageResource(ResUtil.getDrawableId(context, metaFloat));
	}

	public boolean hasNavBar(Context context) {
		boolean hasNavigationBar = false;
		Resources rs = context.getResources();
		int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
		if (id > 0) {
			hasNavigationBar = rs.getBoolean(id);
		}
		try {
			Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
			Method m = systemPropertiesClass.getMethod("get", String.class);
			String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
			if ("1".equals(navBarOverride)) {
				hasNavigationBar = false;
			} else if ("0".equals(navBarOverride)) {
				hasNavigationBar = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return hasNavigationBar;
	}

	private int getNavigationBarHeight() {
		Resources resources = mcontext.getResources();
		int resourceId = resources.getIdentifier("navigation_bar_height",
				"dimen", "android");
		return resources.getDimensionPixelSize(resourceId);
	}

	public static double getDistance(double x1, double y1, double x2, double y2) {
		double d = (x2 - x1) * (x2 - x1) - (y2 - y1) * (y2 - y1);
		return Math.sqrt(d);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// 初始化不透明
		mParams.alpha = 1.0f;
		windowManager.updateViewLayout(this, mParams);

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			xInView = event.getX();
			yInView = event.getY();
			xDownInScreen = event.getRawX();
			yDownInScreen = event.getRawY();
			xInScreen = event.getRawX();
			yInScreen = event.getRawY();
			moveaction = 2;
			break;
		case MotionEvent.ACTION_MOVE:
			xInScreen = event.getRawX();
			yInScreen = event.getRawY();
			updateViewPosition();
			moveaction = 2;
			break;
		case MotionEvent.ACTION_UP:
			double distance = getDistance(xDownInScreen, yDownInScreen, xInScreen, yInScreen);
			DisplayMetrics metric = getResources().getDisplayMetrics();
			float densf = metric.density;
			
			if (densf >= 3.0) {
				// 2K分辨率
				densf = metric.density * 92;
			}
			// 计算点击的距离范围是 1/4 浮标大小
			if (distance < densf) {
				openWebEdit();
				moveaction = 2;

				mRedpoint.setVisibility(View.INVISIBLE);
			} else {
				// 计算到边框的距离，再将浮标移动到四个边框
				moveaction = 1;
				FinalautoMove();
			}
			break;
		default:
			break;
		}
		return true;
	}

	Runnable runnableUi = new Runnable() {
		@Override
		public void run() {
			// 更新界面
			DisplayMetrics dm = new DisplayMetrics();
			windowManager.getDefaultDisplay().getMetrics(dm);
			screenWidth = dm.widthPixels;
			screenHeight = dm.heightPixels;

			int leftd = mParams.x;
			int rightd = screenWidth - mParams.x - FloatBallView.viewWidth;
			int bootomd = screenHeight - mParams.y - FloatBallView.viewHeight;

			int direction = LEFT; // 1 左 2 右 3上 4 下
			int minDistance = leftd;
			if (rightd < minDistance) {
				minDistance = rightd;
				direction = RIGHT;
			}
			/*
			 * 关闭浮标上贴 if (topd < minDistance) { minDistance = topd; direction =
			 * 3; }
			 */
			if (bootomd < minDistance) {
				direction = BOTTOM;
			}
			new autoEdgeTask().execute(direction);
			/*
			 * case 3: // mParams.x = (int) (xInScreen - xInView); mParams.y = 0
			 * - viewHeight / 2 - viewHeight / 3;// - viewHeight/3; break;
			 */
			mParams.alpha = 0.5f;
		}
	};

	class autoEdgeTask extends AsyncTask<Integer, Void, Void> {
		@Override
		protected Void doInBackground(Integer... direct) {
			switch (direct[0]) {
			case LEFT:
				while (mParams.x > -(viewWidth / 2)) {
					mParams.x -= 10;
					publishProgress();
					try {
						Thread.sleep(5);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				mParams.x = -(viewHeight *2/ 3);
				publishProgress();
				break;
			case RIGHT:
				if (hasNavBar(mcontext)) {
					screenWidth += getNavigationBarHeight();
				}
				while (mParams.x < (screenWidth - viewWidth + viewWidth / 2)) {
					mParams.x += 10;
					publishProgress();
					try {
						Thread.sleep(5);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				mParams.x = screenWidth - viewWidth / 3;
				publishProgress();
				break;
			case BOTTOM:
				while (mParams.y < (screenHeight - viewHeight / 2)) {
					mParams.y += 10;
					publishProgress();
					try {
						Thread.sleep(5);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				mParams.y = screenHeight - viewHeight / 3;
				publishProgress();
				break;
			default:
				break;
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			if (mParams instanceof WindowManager.LayoutParams) {
				try {
					windowManager.updateViewLayout(FloatBallView.this,
							mParams);
				} catch (Exception e) {
					// 这里有个问题未解决，只加了捕获异常，在Activity（WindowManager）销毁时仍自动移动
				}
			}
		}
	}

	private void FinalautoMove() {
		new Thread() {
			public void run() {
				for (int i = 0; i < 20; i++) {
					try {
						Thread.sleep(100);
						if (moveaction == 2 || !FloatWindowService.canopenfloat
								|| moveaction == 3) {
							return;
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				handler.post(runnableUi);
			}
		}.start();
	}

	public void setParams(WindowManager.LayoutParams params) {
		mParams = params;
		String packname = mcontext.getPackageName();
		PackageManager pm = mcontext.getPackageManager();
		boolean permission = (PackageManager.PERMISSION_GRANTED == pm
				.checkPermission("android.permission.SYSTEM_ALERT_WINDOW", packname));
		if (!permission) {
			boolean isxiaomi = JudgeMIUI.isMIUI();
			if (isxiaomi) {
				return;
			}
		}
		FinalautoMove();
	}

	private void updateViewPosition() {
		if (xDownInScreen == xInScreen && yDownInScreen == yInScreen) {
			return;
		}
		mParams.x = (int) (xInScreen - xInView);
		mParams.y = (int) (yInScreen - yInView);
		windowManager.updateViewLayout(this, mParams);
	}

	private void openWebEdit() {
		if (mFloatWebView != null) {
			if (mFloatWebView.isShowing())
				return;
		}

		if (!NetworkImpl.isNetworkConnected(mcontext)) {
			Toast.makeText(getContext(), TipMessSingle.ten_networkerr,
					Toast.LENGTH_LONG).show();
			return;
		}
		
		MyWindowManager.turnWindowParams = mParams;
		MyWindowManager.removefloatWindow(mcontext.getApplicationContext());

		FloatWindowService.canopenfloat = false;
		mFloatWebView = new FloatWebView(mcontext, doFloatWebRequest(GuildBaseInfo.getInstance().buildFloatWebParamGuild(mcontext)));
		
		String floatUrl;
		if (GuildBaseInfo.getInstance().getMetaUrl("API_URL").contains("https") && needHttpsFloat(mcontext)){
			floatUrl = SpMmkvUtils.getValue(mcontext, SpMmkvUtils.KEY_HTTPS_FLOAT_URL);
		}else {
			floatUrl = doFloatWebRequest(GuildBaseInfo.getInstance().buildFloatWebParamGuild(mcontext));
		}
		mFloatWebView = new FloatWebView(mcontext, floatUrl);
		mFloatWebView.show();
		
		Window window = mFloatWebView.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(lp); 
	}
	
	public boolean needHttpsFloat(Context context) {
		return SpMmkvUtils.getValue(context, SpMmkvUtils.KEY_HTTPS_FLOAT_URL) != null
			&& !SpMmkvUtils.getValue(context, SpMmkvUtils.KEY_HTTPS_FLOAT_URL).equals("");
	}
}
